package 力扣面试经典150;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2024-03-24
 * Time:14:53
 */

/**
 * 力扣面试经典150:112. 路径总和
 * 简单
 * 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径，这条路径上所有节点值相加等于目标和 targetSum 。如果存在，返回 true ；否则，返回 false 。
 * 叶子节点 是指没有子节点的节点。
 * 示例 1：
 * 输入：root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
 * 输出：true
 * 解释：等于目标和的根节点到叶节点路径如上图所示。
 */
public class hasPathSum {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.right = new TreeNode(1);
        hasPathSum(root,22);
    }
    public static boolean hasPathSum(TreeNode root, int targetSum) {
        if(root == null) {
            return false;
        }

        return dfs(root,0,targetSum);
    }

    private static boolean dfs(TreeNode root, int sum, int targetSum) {
        if(root == null) {
            return false;
        }
        sum += root.val;
        if(sum == targetSum && root.left == null && root.right == null){
            return true;
        }
        return dfs(root.left,sum,targetSum) || dfs(root.right,sum,targetSum);
    }

}
